    //
//  ChooseOrganizationViewController.m
//  BVAttend
//
//  Created by Allen Thomas on 10/19/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "EventSetupViewController.h"
#import "MemberCheckinViewController.h"
#import "BVCMSAppDelegate.h"
#import "HttpConnectionHandler.h"
#import "GenericXMLParser.h"
#import "RoundBoxView.h"

@implementation EventSetupViewController
@synthesize table;
@synthesize organizations;
@synthesize selectedOrganization;

- (void)viewDidLoad {
	NSLog(@"Event Setup viewDidLoad");
	
	self.title = @"Attend";
	
	BVCMSAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	self.organizations = delegate.organizations;
	
	if( [organizations count] == 0 ) {
		[self loadBlackBackGround];
	}
	
	UIImage *background = [UIImage imageNamed: @"background.png"];    
	UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; 
	
	[self.view addSubview: imageView];
	[self.view sendSubviewToBack: imageView];
	[imageView release];	
	
	dtpicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
	dtpicker.datePickerMode = UIDatePickerModeDate;
	[dtpicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
	
	timepicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
	timepicker.datePickerMode = UIDatePickerModeTime;
	timepicker.minuteInterval = 15;
	[timepicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
	
	
	selectedOrganization = 0;
	[self setMeetingDateTimetoSelectedOrganization];
	
	table.backgroundColor = [UIColor clearColor];
}

- (NSString *)dateToString:(NSDate *) theDate {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"MM/dd/yyyy"];
	
	NSString *stringFromDate = [formatter stringFromDate:theDate];
	[formatter release];
	return stringFromDate;
}

- (NSString *)timeToString:(NSDate *) theDate {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"hh:mm a"];
	
	NSString *stringFromDate = [formatter stringFromDate:theDate];
	[formatter release];
	return stringFromDate;
}


#pragma mark Table delegate methods

/*
 Returns number of sections in the table.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomCell";
	
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
	
	cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0];
	cell.detailTextLabel.font = [UIFont systemFontOfSize:14.0];
	
	switch (indexPath.row) {
		case 2:
			cell.textLabel.text		= @"Time";
			cell.detailTextLabel.text = [self timeToString:timepicker.date];
			break;
		case 1:
			cell.textLabel.text		  = @"Date";
			cell.detailTextLabel.text = [self dateToString:dtpicker.date];
			break;
		case 0:
			cell.textLabel.text		  = @"Organization";
			if ( [organizations count] > 0 )
				cell.detailTextLabel.text = [[organizations objectAtIndex:selectedOrganization] valueForKey:@"Name"];
			break;
		default:
			break;
	}

	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Deselect this row, to conform the human interface guidelines
	[tableView  deselectRowAtIndexPath:indexPath  animated:YES]; 
	
	switch (indexPath.row) {
		case 2:
			[self showDatePicker:timepicker withTitle:@"Choose Time"];
			break;
		case 1:
			[self showDatePicker:dtpicker withTitle:@"Choose Date"];
			break;
		case 0:
			[self showPicker];
			break;
		default:
			break;
	}
	
} 


- (void)performAttendance:(id)sender {
	
	MemberCheckinViewController *memberCheckinView = [[MemberCheckinViewController alloc]
													  initWithNibName:@"MemberCheckinView" bundle:[NSBundle mainBundle]];
	memberCheckinView.organizationId = [[organizations objectAtIndex:selectedOrganization] valueForKey:@"Id"];
	memberCheckinView.organizationName = [[organizations objectAtIndex:selectedOrganization] valueForKey:@"Name"];
	
	NSString* datetimeString = [NSString stringWithFormat:@"%@ %@", [self dateToString:dtpicker.date], [self timeToString:timepicker.date]];
	NSDateFormatter *fullDateFormatter = [[NSDateFormatter alloc] init];
	[fullDateFormatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
	
	memberCheckinView.meetingDate = [fullDateFormatter dateFromString:datetimeString];
	
	[self.navigationController pushViewController:memberCheckinView animated:YES];
	[memberCheckinView release];
	[fullDateFormatter release];
	
}


#pragma mark ActionSheets

- (void) showPicker {
	pickerAcc = [[UIActionSheet alloc] initWithTitle:@"Organizations"
													 delegate:self
											cancelButtonTitle:nil
									   destructiveButtonTitle:nil
											otherButtonTitles:nil];	
	
	UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
	pickerView.showsSelectionIndicator = YES;
	pickerView.dataSource = self;
	pickerView.delegate = self;
	[pickerView selectRow:self.selectedOrganization inComponent:0 animated:NO];
	
	// setup actionsheet toolbar
	UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
	pickerToolbar.barStyle = UIBarStyleBlackOpaque;
	[pickerToolbar sizeToFit];
	
	NSMutableArray *barItems = [[NSMutableArray alloc] init];
	
	UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
	[barItems addObject:flexSpace];
	[flexSpace release];
	
	UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pickerDoneAction:)];
	[barItems addObject:doneBtn];
	[doneBtn release];

	[pickerToolbar setItems:barItems animated:YES];
	[barItems release];
	
	// add toolbar to actionsheet
	[pickerAcc addSubview:pickerToolbar];
	[pickerToolbar release];
	
	// add picker to actionsheet
	[pickerAcc addSubview:pickerView];
	[pickerAcc showInView:self.parentViewController.tabBarController.view]; 
	[pickerView release];	
	
	// setup animation movement
	CGRect menuRect = pickerAcc.frame;
	menuRect.origin.y -= 214; //height of picker
	menuRect.size.height = 300;
	pickerAcc.frame = menuRect;
	
}

- (void)pickerDoneAction:(id)sender {
	[pickerAcc dismissWithClickedButtonIndex:0 animated:YES];
	[pickerAcc release];
}

- (void)setMeetingDateTimetoSelectedOrganization {
	if ( [organizations count] > 0 ) {
		NSDateFormatter *timeformatter = [[NSDateFormatter alloc] init];
		[timeformatter setDateFormat:@"hh:mm a"];
		
		NSDate *currentDate = [[NSDate alloc] init];
		NSString *meetingTime = [[organizations objectAtIndex:selectedOrganization] valueForKey:@"MeetingTime"];
		
		[timepicker setDate:[timeformatter dateFromString:meetingTime]];	
		[dtpicker setDate:currentDate];
		
		[timeformatter release];
		[currentDate release];
	}
}
		 
- (void) showDatePicker:(UIDatePicker*)picker withTitle:(NSString*)title {
	datePickerAcc = [[UIActionSheet alloc] initWithTitle:title
													 delegate:self
											cancelButtonTitle:nil
									   destructiveButtonTitle:nil
											otherButtonTitles:nil];
	
	// setup toolbar buttons
	UIToolbar *pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
	pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
	[pickerDateToolbar sizeToFit];
	
	NSMutableArray *barItems = [[NSMutableArray alloc] init];
	UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
	[barItems addObject:flexSpace];
	[flexSpace release];
	
	UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(datePickerDoneAction:)];
	[barItems addObject:doneBtn];
	[doneBtn release];
	
	[pickerDateToolbar setItems:barItems animated:YES];
	[barItems release];
	
	// add toolbar to actionsheet
	[datePickerAcc addSubview:pickerDateToolbar];
	[pickerDateToolbar release];
	
	// add date picker to action sheet
	[datePickerAcc addSubview:picker];
	[datePickerAcc showInView:self.parentViewController.tabBarController.view]; 
	
	// setup animation movement
	CGRect menuRect = datePickerAcc.frame;
	menuRect.origin.y -= 214; //height of picker
	menuRect.size.height = 300;
	datePickerAcc.frame = menuRect;
	
}


- (void)dateChanged:(id)sender {
	[table reloadData];
}

- (void)datePickerDoneAction:(id)sender {
	[datePickerAcc dismissWithClickedButtonIndex:0 animated:YES];
	[datePickerAcc release];
}

#pragma mark PickerView methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
	return [organizations count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	
	return [[organizations objectAtIndex:row] valueForKey:@"Name"];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
	selectedOrganization = row;
	[self setMeetingDateTimetoSelectedOrganization];
	[table reloadData];
}


- (void)loadBlackBackGround
{
	UIView *blackView = [[UIView alloc] initWithFrame:[self.view bounds]];
	
	blackView.backgroundColor = [UIColor blackColor];
	blackView.alpha = 0.4;
	blackView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	
	const CGFloat DEFAULT_LABEL_WIDTH = 200.0;
	const CGFloat DEFAULT_LABEL_HEIGHT = 50.0;
	CGRect labelFrame = CGRectMake(0, 0, DEFAULT_LABEL_WIDTH, DEFAULT_LABEL_HEIGHT);
	UILabel *statement = [[UILabel alloc] initWithFrame:labelFrame];
	statement.text = NSLocalizedString(@"No org available to record attendance", nil);
	statement.textColor = [UIColor whiteColor];
	statement.numberOfLines = 0;
	statement.lineBreakMode = UILineBreakModeWordWrap;
	statement.backgroundColor = [UIColor clearColor];
	statement.shadowColor = [UIColor darkGrayColor];
	statement.textAlignment = UITextAlignmentCenter;
	statement.font = [UIFont boldSystemFontOfSize:18.0];
	statement.autoresizingMask =
	UIViewAutoresizingFlexibleLeftMargin |
	UIViewAutoresizingFlexibleRightMargin |
	UIViewAutoresizingFlexibleTopMargin |
	UIViewAutoresizingFlexibleBottomMargin;
	
	CGFloat totalHeight = statement.frame.size.height;
	labelFrame.origin.x = floor(0.5 * (blackView.frame.size.width - DEFAULT_LABEL_WIDTH));
	labelFrame.origin.y = floor(0.5 * (blackView.frame.size.height - totalHeight));
	statement.frame = labelFrame;	
	
	CGRect boxFrame = labelFrame;
	boxFrame.size.width = boxFrame.size.width + 50;
	boxFrame.size.height = boxFrame.size.height + 50;
	boxFrame.origin.x = boxFrame.origin.x - 25;
	boxFrame.origin.y = boxFrame.origin.y - 25;

	[self.view addSubview:blackView];
	[blackView release];
	
	RoundBoxView *blackBox = [[RoundBoxView alloc] initWithFrame:boxFrame];
	[self.view addSubview:blackBox];
	[blackBox release];

	[self.view addSubview:statement];
	[statement release];
}



#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[dtpicker release];
	[timepicker release];
	[organizations release];
	[table release];
    [super dealloc];
}


@end
